
//% color="#A0522D" iconWidth=50 iconHeight=40
namespace ensemble{

    //% block="加载数据" blockType="tag"
    export function initmodel() {}
    //% block="初始化模块" blockType="command"
    export function init(parameter: any, block: any) {

        Generator.addImport(`import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
import joblib
import warnings
import time
`)   
        Generator.addCode(`warnings.filterwarnings('ignore')`)  
    }

    //% block="读取样本数据集路径[DIR]，设置样本标签[BQ],返回数据存入变量[VAR]" blockType="command"
    //% DIR.shadow="string" DIR.defl="dataset"
    //% BQ.shadow="normal" BQ.defl="1"
    //% VAR.shadow="normal" VAR.defl="data"
    export function readcap(parameter: any, block: any) {
        let DIR=parameter.DIR.code;
        let BQ=parameter.BQ.code;
        let VAR=parameter.VAR.code;
        Generator.addCode(`${VAR} = pd.read_csv(${DIR})
${VAR}['label'] = ${BQ}`)
            
    }

    //% block="合并正负样本[INT]和[TNI]，返回数据存入变量[VAR]" blockType="command"
    //% INT.shadow="normal" INT.defl="data_pos"
    //% TNI.shadow="normal" TNI.defl="data_neg"
    //% VAR.shadow="normal" VAR.defl="data"
    export function readimg(parameter: any, block: any) {
        let INT=parameter.INT.code;
        let TNI=parameter.TNI.code;
        let VAR=parameter.VAR.code;
        Generator.addCode(`${VAR} = pd.concat([${INT}, ${TNI}], ignore_index=True)`)
        
    }
        //% block="处理数据" blockType="tag"
        export function initmodel1() {}
    //% block="对象名[OBJ]将特征数据[X]与标签数据[Y]划分" blockType="command"
    //% OBJ.shadow="normal" OBJ.defl="data"
    //% X.shadow="normal" X.defl="X"
    //% Y.shadow="normal" Y.defl="y"
    
    export function cv_collect_set_winname(parameter: any, block: any) {
        let OBJ=parameter.OBJ.code;
        let X=parameter.X.code;
        let Y=parameter.Y.code;
        Generator.addCode(`${X} = data.drop('label', axis=1)
${Y} = data['label']`)

    }
    // //% block="将特征[VAR2]和标签[VAR3]进行数据集划分 测试集占比[SIZE] 结果存入变量[VAR5]" blockType="command"
    // //% VAR2.shadow="normal" VAR2.defl="X"
    // //% VAR3.shadow="normal" VAR3.defl="y"
    // //% VAR5.shadow="normal" VAR5.defl="dataSplit"
    // //% SIZE.shadow="number" SIZE.defl=0.3
    // export function trainTestSplit(parameter: any, block: any) {
    //     let VAR2=parameter.VAR2.code; 
    //     let VAR3=parameter.VAR3.code; 
    //     let VAR5=parameter.VAR5.code; 
    //     let SIZE=parameter.SIZE.code; 
    //     Generator.addCode(`${VAR5}= train_test_split(${VAR2}, ${VAR3},test_size=${SIZE},random_state=10,stratify=${VAR3})`)

    // }
    //    //% block="从划分后数据集[VAR5]中取[SDATA]" blockType="reporter"
    // //% VAR5.shadow="normal" VAR5.defl="dataSplit"
    // //% SDATA.shadow="dropdown" SDATA.options="SDATA"
    // export function SDataGet(parameter: any, block: any) {
    //     let VAR5=parameter.VAR5.code; 
    //     let SDATA=parameter.SDATA.code; 

    //     Generator.addCode(`${VAR5}[${SDATA}]`)

    // }
    //% block="随机划分特征集[X]标签集[Y]样本占比[SIZE]返回划分的训练特征集[XTRAIN]测试特征集[Xtest]训练标签集[YTRAIN]测试标签集[Ytest]" blockType="command"
    //% SIZE.shadow="range" SIZE.params.min=0    SIZE.params.max=1    SIZE.defl=0.3
    //% X.shadow="normal" X.defl="X"
    //% Y.shadow="normal" Y.defl="y"
    //% XTRAIN.shadow="normal" XTRAIN.defl="X_train"
    //% Xtest.shadow="normal" Xtest.defl="X_test"
    //% YTRAIN.shadow="normal" YTRAIN.defl="y_train"
    //% Ytest.shadow="normal" Ytest.defl="y_test"
    export function train_test_split(parameter: any, block: any) {
        let x=parameter.X.code;
        let y=parameter.Y.code;
        let size=parameter.SIZE.code;
 
        let xtrain=parameter.XTRAIN.code;
        let ytrain=parameter.YTRAIN.code;
        let xtest=parameter.Xtest.code;
        let ytest=parameter.Ytest.code;
        Generator.addCode(`${xtrain}, ${xtest}, ${ytrain}, ${ytest} = train_test_split(${x},${y}, test_size=${size}, random_state=42)\n`)

    }

    //% block="初始化队列" blockType="command"
    export function init_queue0(parameter: any, block: any) {
        Generator.addCode(`record_queue = Queue()`)
        }
    //% block="将[V1][V2][V3]数据放入队列" blockType="command"
    //% V1.shadow="normal" V1.defl="v1"
    //% V2.shadow="normal" V2.defl="v2"
    //% V3.shadow="normal" V3.defl="v3"
    export function record_queue(parameter: any, block: any) {
        let v1=parameter.V1.code;
        let v2=parameter.V2.code;
        let v3=parameter.V3.code;
        Generator.addImport(`from queue import Queue`)
        Generator.addCode(`record_queue.put((${v1}, ${v2}, ${v3}))`)
    }
    //% block="启动线程" blockType="command"
    export function init_queue(parameter: any, block: any) {
        Generator.addImport(`from queue import Queue
import threading`)
        Generator.addCode(`
if len(record_queue.queue) >= 3 * 10: 
    threading.Thread(target=recording_, args=(record_queue,)).start()`)
    }
    //% block="队列函数" blockType="hat"
    export function init_queue1(parameter: any, block: any) {
        Generator.addEvent("abc",`recording_`,`queue`,"")
        
        
    }
    //% block="获取队列中[V1][V2][V3]数据" blockType="command"
    //% V1.shadow="normal" V1.defl="v1"
    //% V2.shadow="normal" V2.defl="v2"
    //% V3.shadow="normal" V3.defl="v3"
    export function get_queue(parameter: any, block: any) {
        let v1=parameter.V1.code;
        let v2=parameter.V2.code;
        let v3=parameter.V3.code;
        Generator.addCode(`${v1}, ${v2}, ${v3} = record_queue.get()`)
    }
    //% block="从[VX][VY][VZ]数据中计算特征，将数据存入变量[VAR]" blockType="command"
    //% VX.shadow="normal" VX.defl="vx"
    //% VY.shadow="normal" VY.defl="vy"
    //% VZ.shadow="normal" VZ.defl="vz"
    //% VAR.shadow="normal" VAR.defl="statistics_feature"
    export function initmodel2(parameter: any, block: any) {
        let vx= parameter.VX.code;
        let vy= parameter.VY.code;
        let vz= parameter.VZ.code;
        let VAR=parameter.VAR.code;
        Generator.addImport(`import numpy as np`)
        Generator.addCode(`
x_axis = ${vx} 
y_axis = ${vy}
z_axis = ${vz}   
statistics_feature = []
statistics_feature.append(np.mean(x_axis))  # X轴均值
statistics_feature.append(np.mean(y_axis))  # Y轴均值
statistics_feature.append(np.mean(z_axis))  # Z轴均值
statistics_feature.append(np.std(x_axis))   # X轴标准差
statistics_feature.append(np.std(y_axis))   # Y轴标准差
statistics_feature.append(np.std(z_axis))   # Z轴标准差
statistics_feature.append(np.corrcoef(x_axis, y_axis)[0][1])  # X与Y的相关系数
statistics_feature.append(np.corrcoef(y_axis, z_axis)[0][1])  # Y与Z的相关系数
statistics_feature.append(np.corrcoef(x_axis, z_axis)[0][1])  # X与Z的相关系数)
${VAR} = np.nan_to_num(statistics_feature)`) 
    
    }

    //% block="清空队列" blockType="command"
    export function init_queue2(parameter: any, block: any) {
        Generator.addCode(`while not queue.empty():
    queue.get()`)
    }

    //% block="模型操作" blockType="tag"
    export function initmodel4() {}
    //% block="初始化随机森林分类器对象[OBJ]，决策树数量[NUM] 最大深度[DEP]" blockType="command"
    //% OBJ.shadow="normal" OBJ.defl="rf_model"
    //% NUM.shadow="normal" NUM.defl=100
    //% DEP.shadow="normal" DEP.defl=None

    export function Sklearn_initread(parameter: any, block: any) {
        let obj=parameter.OBJ.code;  
        let num=parameter.NUM.code;
        let dep=parameter.DEP.code;
        Generator.addCode(`${obj} = RandomForestClassifier(
    n_estimators=${num},       
    max_depth=${dep},         
    random_state=42,        
    n_jobs=-1
)`) 
    }
    //% block="随机森林模型[OBJ]使用特征集[XTRAIN]和标签集[YTRAIN]数据进行训练模型" blockType="command"
    //% OBJ.shadow="normal" OBJ.defl="rf_model"
    //% XTRAIN.shadow="normal" XTRAIN.defl="X_train"
    //% YTRAIN.shadow="normal" YTRAIN.defl="y_train"
    export function train(parameter: any, block: any) {
        let obj=parameter.OBJ.code;
        let xtrain=parameter.XTRAIN.code;
        let ytrain=parameter.YTRAIN.code;
        Generator.addCode(`${obj}.fit(${xtrain}, ${ytrain})`)
    }
    //% block="随机森林模型[OBJ]对测试集[DATA]数据进行预测并返回标签结果" blockType="command"
    //% OBJ.shadow="normal" OBJ.defl="rf_model"
    //% DATA.shadow="normal" DATA.defl="X_test"
    export function predict(parameter: any, block: any) {
        let obj=parameter.OBJ.code;  
        let data=parameter.DATA.code;  
        Generator.addCode(`y_pred = ${obj}.predict(${data})`) 
    }  
    //% block="预测标签结果" blockType="reporter"
    export function predictay_pred(parameter: any, block: any) {
        Generator.addCode(`(y_pred)`) 
    }  

    //% block="对真实标签[DATA]、预测标签[BQ]数据进行预测并返回结果" blockType="command"
    //% DATA.shadow="normal" DATA.defl="y_test"
    //% BQ.shadow="normal" BQ.defl="y_pred"
    export function predict1(parameter: any, block: any) {
        let data=parameter.DATA.code;
        let bq=parameter.BQ.code;
        Generator.addCode(`accuracy_valve = accuracy_score(${data}, ${bq})
classification_report = classification_report(${data}, ${bq})
confusion_matrix = confusion_matrix(${data}, ${bq})`) 
    }  
    //% block="[VALVE]结果" blockType="reporter"
    //% VALVE.shadow="dropdown" VALVE.options="VALVE"
    export function predictaaccuracy_valve(parameter: any, block: any) {
        let valve=parameter.VALVE.code;
        Generator.addCode(`(${valve})`) 
    }  
    //% block="使用随机森林模型[OBJ],保存模型路径[PATH]" blockType="command"
    //% OBJ.shadow="normal" OBJ.defl="rf_model"
    //% PATH.shadow="string" PATH.defl="jumping_jack_rf_model.pkl"
    export function savemodel(parameter: any, block: any) {
        let obj=parameter.OBJ.code;
        let path=parameter.PATH.code;
        Generator.addCode(`joblib.dump(${obj}, ${path})`) 
    } 
    //% block="对象名[OBJ]加载模型路径[PATH]" blockType="command"
    //% OBJ.shadow="normal" OBJ.defl="model"
    //% PATH.shadow="string" PATH.defl="jumping_jack_rf_model.pkl"
    export function loadmodel(parameter: any, block: any) {
        let obj=parameter.OBJ.code;
        let path=parameter.PATH.code;
        Generator.addCode(`${obj} = joblib.load(${path})`) 
    }
    //% block="对象名[OBJ]预测特征数据[DATA]并返回结果存入变量[VAR]" blockType="command"
    //% OBJ.shadow="normal" OBJ.defl="model"
    //% DATA.shadow="normal" DATA.defl="statistics_feature"
    //% VAR.shadow="normal" VAR.defl="prediction"
    export function predict2(parameter: any, block: any) {
        let obj=parameter.OBJ.code;
        let data=parameter.DATA.code;
        let var1=parameter.VAR.code;
        Generator.addCode(`${var1} = ${obj}.predict([${data}])`) 
    }
}
